import {
	LOGIN_STATUS,
	USER_ID,
	USER_INFO
} from '@/config/cache';
import Cache from '@/utils/cache'
import {
	dateFormat
} from '@/utils/util.js'
import {
	loginByCode,
	getUserPhone,
	getWxPhone,
	getUserInfo,
	updateUserInfo
} from '@/api/user.js'

// 登陆成功后执行
const loginSuccess = (commit, {
	token,
	userId,
	user
}) => {
	// 过期时间30天
	const expiryTime = 30 * 86400
	// 保存tokne和userId到缓存
	Cache.set(USER_ID, userId, expiryTime)
	Cache.set(USER_INFO, user, expiryTime)
	Cache.set(LOGIN_STATUS, token, expiryTime)
	// 记录到store全局变量
	commit('SET_TOKEN', token)
	commit('SET_USER_INFO', user)
	commit('SET_USER_ID', userId)
}

// 加工userInfo数据
const formatUserInfo = userInfo => {
	// 格式化会员过期时间
	userInfo.expireTime = dateFormat('YYYY-mm-dd', new Date(userInfo.expireTime))
	// 判断会员过期是否在7天后过期
	let tempDays = (new Date(userInfo.expireTime) - new Date()) / (1000 * 60 * 60 * 24)
	userInfo.isMemberExpired = (tempDays < 8)
	return userInfo
}

const user = {
	state: {
		// 用户认证token
		token: Cache.get(LOGIN_STATUS) || false,
		// 用户ID
		userId: null,
		userInfo: {},
	},

	mutations: {
		SET_TOKEN: (state, value) => {
			state.token = value
		},
		SET_USER_INFO: (state, value) => {
			state.userInfo = value ? formatUserInfo(value) : {}
		},
		SET_USER_ID: (state, value) => {
			state.userId = value
		}
	},

	actions: {
		getCode() {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: res => {
						resolve(res.code)
					},
					fail: reject
				})
			})
		},

		// code静默登录
		silenceLogin({
			commit,
			dispatch
		}, data) {
			return new Promise(async (resolve, reject) => {
				let code = await dispatch('getCode')
				loginByCode(code).then(res => {
					loginSuccess(commit, res.data)
					resolve(res.data)
				}).catch(reject)
			})
		},

		// 微信小程序一键授权登录(授权手机号)
		loginByWxPhone({
			commit,
			dispatch
		}, code) {
			return new Promise(async (resolve, reject) => {
				await dispatch('silenceLogin')
				getWxPhone(code).then(res => {
						resolve(res.data)
					})
					.catch(reject)
			})
		},

		// 退出登录
		logout({
			commit
		}, data) {
			return new Promise((resolve, reject) => {
				// 删除缓存中的tokne和userId
				Cache.clear(USER_ID)
				Cache.clear(USER_INFO)
				Cache.clear(LOGIN_STATUS)
				commit('SET_TOKEN', '')
				commit('SET_USER_ID', null)
				commit('SET_USER_INFO', {})
				resolve()
			})
		},

		// 获取用户信息
		getUserInfo({
			commit
		}, data) {
			return new Promise((resolve, reject) => {
				getUserInfo().then(res => {
					let {
						user,
						userId
					} = res.data
					commit('SET_USER_INFO', user)
					resolve(user)
				})
			})
		},

		// 更新用户信息
		updateUserInfo({
			commit
		}, data) {
			return new Promise((resolve, reject) => {
				updateUserInfo(data).then(res => {
					let {
						user,
						userId
					} = res.data
					commit('SET_USER_INFO', user)
					resolve(user)
				})
			})
		},


	}
}

export default user
